package com.fh.quartz;

import com.fh.feign.OrderCloseClient;
import com.fh.feign.StatusUpdateClient;
import com.fh.feign.TimeoutQueryClient;
import com.fh.model.Orders;
import com.github.wxpay.sdk.WXPay;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeoutCheck {
    @Resource
    private TimeoutQueryClient timeoutQueryClient;
    @Resource
    private StatusUpdateClient statusUpdateClient;
    @Resource
    private OrderCloseClient orderCloseClient;


    @Scheduled(cron = "0/3 * * * * ?")
    public void checkAndCloseOrder() {
        List<Orders> orders = timeoutQueryClient.query();
        //访问微信平台接口 确定状态
        //如果支付了 状态改为2
        MyPayConfig config = new MyPayConfig();
        WXPay wxPay = new WXPay(config);
        try {
            for (Orders order : orders) {
                Map<String, String> params = new HashMap<>();
                params.put("out_trade_no", order.getOrderId());
                Map<String, String> resp = wxPay.orderQuery(params);
                if ( "SUCCESS".equals( resp.get("trade_state"))) {
                    Orders orders1 = new Orders();
                    orders1.setOrderId(order.getOrderId());
                    orders1.setStatus("2");
                    statusUpdateClient.update(orders1);
                } else if ("NOTPAY".equals(resp.get("trade_state"))) {
                    Map<String, String> map = wxPay.orderQuery(params);
                    orderCloseClient.close(order.getOrderId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
